﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigLession
{
    internal class ConfigHelper
    {
        Configuration config;
        ExeConfigurationFileMap exeConfig = new ExeConfigurationFileMap();
        public ConfigHelper()
        {
            exeConfig.ExeConfigFilename = @"E:\Project\ConfigLession\App.config";
            config = ConfigurationManager.OpenMappedExeConfiguration(exeConfig,ConfigurationUserLevel.None);  //打开配置文件（，所有人都可以打开修改配置文件）
        }

        /// <summary>
        /// 得到AppSettings所有节点
        /// </summary>
        /// <returns></returns>
        public string[] ReadAppSettings()
        {
            return config.AppSettings.Settings.AllKeys;
        }

        /// <summary>
        /// 得到AppSetting对应节点
        /// </summary>
        /// <returns></returns>
        public string ReadAppSetting(string key)
        {
            return config.AppSettings.Settings[key].Value;
        }

        /// <summary>
        /// 修改 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void WriteAppSetting(string key, string value)
        {
            config.AppSettings.Settings[key].Value = value;
            config.Save();
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        public void DelAppSetting(string key)
        {
            config.AppSettings.Settings.Remove(key);
            config.Save();
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="key"></param>
        public void AddAppSetting(string key,string value)
        {
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save();
        }

        /// <summary>
        /// 得到connectionString节点数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadconnectionString(string key)
        {
            return config.ConnectionStrings.ConnectionStrings[key].ConnectionString;
        }
    }
}
